package com.jinlejia.erp.adapter.prospect;

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.utils.ViewHolderUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

/**
 * @author 王进 on 2018/12/28.
 */

public class UploadImageGridViewAdapter extends BaseAdapter {

    private final ArrayList<Source> sources = new ArrayList<>();

    private final Context mContext;

    private final UploadListener listener;

    private int maxShowCount;
    private final String mTitle;
    private final Source EMPTY_SOURCE = Source.empty();
    private boolean hasSubdivided;
    public UploadImageGridViewAdapter(String title, Context context, int maxShowCount,boolean hasSubdivided, UploadListener listener) {
        this.mContext = context;
        this.maxShowCount = maxShowCount;
        this.listener = listener;
        this.mTitle = title;
        this.hasSubdivided = hasSubdivided;
    }


    @Override
    public int getCount() {
        int size = sources.size();
        if (size == 0) {
            sources.add(EMPTY_SOURCE);
        }
        return sources.size();
    }

    public boolean isHasSubdivided() {
        return hasSubdivided;
    }

    public int getSourceCount() {
        int count = 0;
        for (Source s : sources) {
            if (!s.isEmpty()) {
                count = count + 1;
            }
        }
        return count;
    }

    private int getLastCount() {
        int count = 0;
        for (Source s : sources) {
            if (!s.isEmpty()) {
                count = count + 1;
            }
        }
        return maxShowCount - count;
    }

    @Override
    public Source getItem(int position) {
        return sources.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_prospect_upload_image, parent, false);
        }
        final Source source = sources.get(position);
        final ImageView showImageView = ViewHolderUtil.get(convertView, R.id.showImageView);
        final ImageView noteImageView = ViewHolderUtil.get(convertView, R.id.noteImageView);
        final ImageView closeImage = ViewHolderUtil.get(convertView, R.id.closeImage);
        final TextView houseInfoTextView = ViewHolderUtil.get(convertView, R.id.houseInfoTextView);
        final TextView houseNameTextView = ViewHolderUtil.get(convertView, R.id.houseNameTextView);
        final TextView acreageTextView = ViewHolderUtil.get(convertView,R.id.acreageTextView);
        final LinearLayout houseInfoLayout = ViewHolderUtil.get(convertView, R.id.houseInfoLayout);
        final ImageView arrowImage = ViewHolderUtil.get(convertView,R.id.arrowImage);
        final RelativeLayout reloadLayout = ViewHolderUtil.get(convertView, R.id.reloadLayout);
        final TextView reloadTextView = ViewHolderUtil.get(convertView, R.id.reloadTextView);
        //region 设置图片
        String pictureUrl = source.getPictureUrl();
        if (!TextUtils.isEmpty(pictureUrl)) { //显示用户选择的图片
            int indexOf = pictureUrl.indexOf(File.separator);
            if (indexOf==-1){
                pictureUrl = ApiConfig.MAGEHEADER_URL() + pictureUrl;
            }
            Glide.with(mContext).load(pictureUrl).placeholder(R.mipmap.ic_no_img).into(showImageView);
            showImageView.setVisibility(View.VISIBLE);
            noteImageView.setVisibility(View.GONE);
            closeImage.setVisibility(View.VISIBLE);
        } else {
            showImageView.setImageURI(null);
            showImageView.setVisibility(View.GONE);
            noteImageView.setVisibility(View.VISIBLE);
            closeImage.setVisibility(View.GONE);
        }
        //endregion

        //region 显示提示文本
        //显示 房间名称
        if (!TextUtils.isEmpty(source.getViewHouseName())){
            houseNameTextView.setText(source.getViewHouseName());
        }else if (!TextUtils.isEmpty(source.getHouseName())){
            houseNameTextView.setText(source.getHouseName());
        }

        if (TextUtils.isEmpty(source.getHouseInfo())) {
            houseNameTextView.setVisibility(View.GONE);
        } else {
            houseNameTextView.setVisibility(View.VISIBLE);
        }
        //显示面积
        if (TextUtils.isEmpty(source.getAcreage())){
            acreageTextView.setVisibility(View.GONE);
        }else {
            acreageTextView.setVisibility(View.VISIBLE);
            acreageTextView.setText(String.format("%s㎡",source.getAcreage()));
        }

        //显示房间基本信息
        if (source.simpleInfo() == null) {
            houseInfoTextView.setVisibility(View.INVISIBLE);
        } else {
            houseInfoTextView.setVisibility(View.VISIBLE);
            houseInfoTextView.setText(source.simpleInfo());
        }
        if (!TextUtils.isEmpty(source.getPictureUrl())) {
            if (!hasSubdivided){
                houseNameTextView.setVisibility(View.GONE);
                houseInfoLayout.setOnClickListener(null);
            } else {
                houseNameTextView.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(source.getHouseName())) {
                    houseNameTextView.setText("分间名称");
                    arrowImage.setVisibility(View.VISIBLE);
                }
                houseInfoLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (listener != null) {
                            listener.onSelectSubdivided(sources,source);
                        }
                    }
                });
            }
        } else {
            houseInfoLayout.setOnClickListener(null);
        }

        if (source.getUploadState() == 0) { //上传成功
            reloadLayout.setVisibility(View.GONE);
            reloadTextView.setVisibility(View.GONE);
            reloadLayout.setOnClickListener(null);
        } else if (source.getUploadState() == 1) { //上传中
            reloadLayout.setVisibility(View.VISIBLE);
            reloadTextView.setVisibility(View.GONE);
            reloadLayout.setOnClickListener(null);
        } else if (source.getUploadState() == 2) { //上传失败
            reloadLayout.setVisibility(View.VISIBLE);
            reloadTextView.setVisibility(View.VISIBLE);
            reloadLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onReloadPicture(source);
                    }
                }
            });
        }
        //endregion

        showImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onPreviewViePicture(sources,position,source);
                }
            }
        });
        noteImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onSelectPicture(getLastCount());
                }
            }
        });
        closeImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Source tempSource = sources.get(position);
                removeSource(tempSource);

            }
        });

        if (acreageTextView.getVisibility()==View.VISIBLE || houseNameTextView.getVisibility()==View.VISIBLE){
            arrowImage.setVisibility(View.VISIBLE);
        }else {
            arrowImage.setVisibility(View.GONE);
        }
        return convertView;
    }

    public void updateSourceInfo(Source source){
        updateSource(source,true);
    }
    private synchronized void updateSource(Source source,boolean isInfo){
        synchronized (sources){
            for (Source s : sources) {
                if (s.id == source.id) {
                    if (source.getUploadState()==1){
                    }
                    if (isInfo){
                        s.copyInfo(source);
                    }else {
                        s.copy(source);
                    }
                }else {
                    if (TextUtils.equals(s.getHouseName(),source.getHouseName())){
                        s.setHouseName(null);
                        s.setWindows(null);
                        s.setAcreage(null);
                        s.setOrientation(null);
                        s.setViewHouseName(null);
                    }
                }
            }
        }
    }

    public void updateSource(Source source) {
        updateSource(source,false);
    }

    private void removeSource(Source source) {
        for (Source s : sources) {
            if (s.isEmpty()) {
                sources.remove(s);
            }
        }
        sources.remove(source);
        if (sources.size() < maxShowCount) {
            sources.add(EMPTY_SOURCE);
        }
        notifyDataSetChanged();
    }
    private int idIndex=0;
    public void addSource(Source source) {
        if (maxShowCount==1){
            sources.clear();
        }
        for (int i = 0; i < sources.size(); i++) {
            Source s = sources.get(i);
            if (s.isEmpty()) {
                sources.remove(s);
                continue;
            }
            s.id = i+1;
            idIndex = s.id;
        }
        idIndex = idIndex +1;
        source.id = idIndex;
        sources.add(source);
        if (sources.size() < maxShowCount) {
            sources.add(EMPTY_SOURCE);
        }
    }

    @SuppressWarnings("unchecked")
    public ArrayList<Source> getSources() {
        ArrayList<Source> clone = (ArrayList<Source>) sources.clone();
        for (Source source:clone) {
            if (source.isEmpty()){
                clone.remove(source);
            }
        }
        return clone;
    }

    public boolean check() {
        for (Source s : sources) {
            if (!s.valueIsAll()) return false;
        }
        return true;
    }

    public interface UploadListener {
        void onSelectPicture(int lastCount);

        void onSelectSubdivided(ArrayList<Source> sources, Source source);

        void onPreviewViePicture(ArrayList<Source> sources, int position, Source source);

        void onReloadPicture(Source source);
    }

    public static class Source implements Parcelable {
        private int id;
        private String pictureUrl; //图片的地址
        private String houseName; //房间名称
        private String viewHouseName; //缩略的房间名称，只有显示作用，不会进行上传
        private String acreage; //面积
        private String orientation; //朝向
        private String windows; //窗户种类
        private int uploadState; //0:上传成功 1:上传中 2:上传失败
        private String serverUrl; //服务器的地址，用来上传
        private boolean empty;

        public Source() {

        }


        protected Source(Parcel in) {
            id = in.readInt();
            pictureUrl = in.readString();
            houseName = in.readString();
            viewHouseName = in.readString();
            acreage = in.readString();
            orientation = in.readString();
            windows = in.readString();
            uploadState = in.readInt();
            serverUrl = in.readString();
            empty = in.readByte() != 0;
        }

        public static final Creator<Source> CREATOR = new Creator<Source>() {
            @Override
            public Source createFromParcel(Parcel in) {
                return new Source(in);
            }

            @Override
            public Source[] newArray(int size) {
                return new Source[size];
            }
        };

        public void setServerUrl(String serverUrl) {
            this.serverUrl = serverUrl;
        }

        public String getServerUrl() {
            return serverUrl;
        }

        boolean valueIsAll() {
            return !(TextUtils.isEmpty(acreage)|| TextUtils.isEmpty(orientation) || TextUtils.isEmpty(windows)
                    || TextUtils.isEmpty(pictureUrl) || TextUtils.isEmpty(houseName));
        }

        public void setUploadState(int uploadState) {
            this.uploadState = uploadState;
        }

        public int getId() {
            return id;
        }

        public int getUploadState() {
            return uploadState;
        }

        String simpleInfo(){
            if (orientation == null && windows == null) {
                return null;
            }
            String or = null;
            if (orientation!=null){ //如果只有朝向
                or = orientation;
                or = or.replace(","," ");
                if (windows==null){
                    return or;
                }else {
                    return String.format(Locale.CHINESE, "%s %s", or, windows);
                }
            }
            return windows;
        }

        public String getHouseInfo() {
            String result;
            String acreage_ = "";
            if (!TextUtils.isEmpty(acreage)){
                acreage_ = acreage+"㎡";
            }
            String orientation_ = "";
            if (!TextUtils.isEmpty(orientation)){
                orientation_ = orientation;
                if (!TextUtils.isEmpty(acreage)){
                    orientation_ = " "+orientation_;
                }
            }
            String windows_ = "";
            if (!TextUtils.isEmpty(windows)){
                windows_ = windows;
                if (!TextUtils.isEmpty(orientation)){
                    windows_ = " "+windows_;
                }
            }
            result = acreage_ + orientation_ + windows_;
            return result;
        }

        public String getViewHouseName() {
            if (viewHouseName==null){
                if (houseName!=null){
                    if (houseName.contains("室内照片")){
                        viewHouseName = houseName.replace("室内照片","室内");
                    }else if (houseName.contains("卫生间")){
                        viewHouseName = houseName.replace("卫生间","卫");
                    }else if (houseName.contains("厨房")){
                        viewHouseName = houseName.replace("厨房","厨");
                    }
                }
            }
            return viewHouseName;
        }

        public void setViewHouseName(String viewHouseName) {
            this.viewHouseName = viewHouseName;
        }

        public String getHouseName() {
            return houseName;
        }

        public void setHouseName(String houseName) {
            this.houseName = houseName;
        }


        public String getAcreage() {
            return acreage;
        }

        public void setAcreage(String acreage) {
            this.acreage = acreage;
        }

        public String getOrientation() {
            return orientation;
        }

        public void setOrientation(String orientation) {
            this.orientation = orientation;
        }

        public String getWindows() {
            return windows;
        }

        public void setWindows(String windows) {
            this.windows = windows;
        }

        Source(boolean empty) {
            this.empty = empty;
        }

        boolean isEmpty() {
            return empty;
        }

        public void setPictureUrl(String pictureUrl) {
            this.pictureUrl = pictureUrl;
        }

        public String getPictureUrl() {
            return pictureUrl;
        }

        public static Source empty() {
            return new Source(true);
        }


        private void copyInfo(Source source){
            setHouseName(source.houseName);
            setAcreage(source.acreage);
            setOrientation(source.orientation);
            setWindows(source.windows);
            setViewHouseName(source.viewHouseName);
        }

        public void copy(Source source) {
            id = source.id;
            setPictureUrl(source.pictureUrl);
            setHouseName(source.houseName);
            setAcreage(source.acreage);
            setOrientation(source.orientation);
            setWindows(source.windows);
            setViewHouseName(source.viewHouseName);
            empty = source.empty;
            uploadState = source.uploadState;

        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(id);
            dest.writeString(pictureUrl);
            dest.writeString(houseName);
            dest.writeString(viewHouseName);
            dest.writeString(acreage);
            dest.writeString(orientation);
            dest.writeString(windows);
            dest.writeInt(uploadState);
            dest.writeString(serverUrl);
            dest.writeByte((byte) (empty ? 1 : 0));
        }
    }
}
